﻿using CsvHelper;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Delphi.Mimir.Data.Load {
    public class CsvLoader<T> {
        public CsvLoader() {
        }

        // Copied form http://www.davepaquette.com/archive/2014/03/18/seeding-entity-framework-database-from-csv.aspx
        public static IList<T> LoadCsv(string resourceName, Encoding encoding) {
            Assembly assembly = Assembly.GetExecutingAssembly();
            
            IList<T> data = new List<T>();

            using (Stream stream = assembly.GetManifestResourceStream(resourceName)) {
                using (StreamReader reader = new StreamReader(stream, encoding)) {
                    CsvReader csvReader = new CsvReader(reader);
                    csvReader.Configuration.WillThrowOnMissingField = false;
                    data = csvReader.GetRecords<T>().ToList<T>();
                }
            }
            return data;
        }

        // Copied form http://blog.developers.ba/bulk-insert-generic-list-sql-server-minimum-lines-code/
        public static void BulkLoad(IList<T> data, string tableName, int batchSize = 1000) {
            using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Delphi"].ConnectionString)) {
                connection.Open();
                SqlTransaction transaction = connection.BeginTransaction();
                using(var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction)) {
                    bulkCopy.BatchSize = batchSize;
                    bulkCopy.DestinationTableName = tableName;
                    try {
                        bulkCopy.WriteToServer(data.AsDataTable());
                        transaction.Commit();
                    } catch (Exception) {
                         transaction.Rollback();
                         connection.Close();
                     }
                    
                    connection.Close();
                }
            }
        }
    }
}
